package com.ivan.controller;

import cn.hutool.core.util.StrUtil;
import com.ivan.config.JwtConfig;
import com.ivan.utils.CheckResult;
import com.ivan.utils.CommonCode;
import com.ivan.utils.JwtUtils;
import com.ivan.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author 11900
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.ivan.controller
 * @Description: TODO
 * @date 2020/4/27 22:27
 */
@RestController
@RequestMapping("/jwt")
public class JwtController {

    @Autowired
    private JwtConfig jwtConfig;


    @GetMapping("/testAll")
    public ResultUtil testAll(HttpServletRequest request){
        String token = request.getHeader(jwtConfig.getHeard());
        if(StrUtil.isNotEmpty(token)){
            CheckResult checkResult = JwtUtils.validateJWT(token);
            if (checkResult.isSuccess()){
                String newToken = JwtUtils.createJWT(checkResult.getClaims().getId(),checkResult.getClaims().getIssuer(),checkResult.getClaims().getSubject(),jwtConfig.getExpiretime()*20*1000);
               return ResultUtil.ok(checkResult.getClaims().getSubject(),newToken);
            }
        }

        return ResultUtil.build(CommonCode.USERNOTLOGIN);
    }

    @PostMapping("/loginjwt")
    public ResultUtil loginjwt(String username,String password){
        if(StrUtil.isNotEmpty(username)&&StrUtil.isNotEmpty(password)){
            //认证信息，用户名和密码实际访问数据库
            try {
                if(username.equalsIgnoreCase(password)){
                    String token = JwtUtils.createJWT(UUID.randomUUID().toString(), jwtConfig.getIss(), username, jwtConfig.getExpiretime()*20 * 1000);
                   return ResultUtil.ok(null,token);

                }
            }catch (Exception e){
                return ResultUtil.build(CommonCode.USERNOTLOGIN);
            }

        }
        return ResultUtil.build(CommonCode.USERNOTLOGIN);
    }
}
